package auth

import (
	"beergo/app/com/models"
	"beergo/lib/event"
	"encoding/json"
)
import "beergo/lib/tool"
import "github.com/beego/beego/v2/server/web/context"

func init() {
	ArticleAuth()
}

func ArticleAuth() {
	event.ListenJoin("ArticleAuth", func(v interface{},ctx *context.Context) {
		url := ctx.Input.URL()
        		access := true
        		message := "access granted!"
        		switch url {
        		case "/admin/Article/info":
        			access = true
        		case "/admin/Article/scan":
					AutoAdd(ctx)
        			access = true
        		case "/admin/Article/list":
        			access = true
        		case "/admin/Article/create":
        			access = true
        		case "/admin/Article/update":
        			access = true
        		case "/admin/Article/edit":
        			access = true
        		case "/admin/Article/copy":
        			access = true
        		case "/admin/Article/delete":
        			//access = false
        			//message = "access denied!"
        		case "/admin/Article/choice":
        			access = true
        		case "/admin/Article/category":
        			access = true
        		default:
        			if len(tool.MatchAll(url, "/admin/Article/[0-9]"))>0 {
        				//edit
        				access = true
        			}else if  len(tool.MatchAll(url, "/admin/Article/[0-9]/(.+?)"))>0  {
        				access = true
        			}else{
        				access = true
        			}
        		}
        		auth ,_ := v.(*event.AuthEvent)
        		auth.Access = access
        		auth.Message = message
	})
}

type M struct {
	Id      int `json:"id"`
	//Product int `json:"product"`
}

func AutoAdd(ctx *context.Context) {
	m := new(M)
	err := json.Unmarshal(ctx.Input.RequestBody, &m)
	if err != nil {
		return
	}
	id := m.Id
	//if m.Product > 0 {
	//	//子选项
	//	id = m.Product
	//}
	p := models.Article{Id: id}
	tool.JsonLog(p)
	p.Read()
	p.Reads++
	p.Save()
}
